package com.xb.p27_servicelifecycle;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;

public class MainActivity extends AppCompatActivity {
    Intent intent=null;
    MyServiceConnection conn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViewById(R.id.service_start).setOnClickListener(new MyClick());
        findViewById(R.id.service_bind).setOnClickListener(new MyClick());
        findViewById(R.id.service_unbind).setOnClickListener(new MyClick());
        findViewById(R.id.service_stop).setOnClickListener(new MyClick());

        intent=new Intent(this,MyService.class);
        conn=new MyServiceConnection();
    }


    private int flag=0;
    class MyClick implements View.OnClickListener{

        @Override
        public void onClick(View v) {
            switch(v.getId()){
                case R.id.service_start:
                    startService(intent);
                    break;
                case R.id.service_bind:
                    if (++flag>1){
                        Log.i("MyServiceLife","再次绑定，当前flag="+flag);
                    }
                    bindService(intent,conn, Context.BIND_AUTO_CREATE);
                    break;
                case R.id.service_unbind:
                    unbindService(conn);
                    break;
                case R.id.service_stop:
                    stopService(intent);
                    break;

            }
        }
    }

    //定义绑定服务
    public class MyServiceConnection implements ServiceConnection{

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }

}